package cn.fl.prjprddtlgps.service.impl;

import cmm.comm.facade.framework.api.ISysFilesApiService;
import cmm.comm.facade.upload.condition.SysUlFilesRecQueryCondition;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.ISysUsrApiService;
import cmm.user.facade.system.dto.SysUsrDTO;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.deviceinfo.api.IDeviceInfoApiService;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.preloan.condition.PrjPrdDtlGpsQueryCondition;
import cn.fl.preloan.dto.PrjPrdDtlGpsPageResponseDTO;
import cn.fl.preloan.dto.gps.GpsAddressDTO;
import cn.fl.preloan.dto.gps.GpsDeviceDTO;
import cn.fl.prjprddtlgps.condition.PrjPrdDtlGpsQC;
import cn.fl.preloan.dto.PrjPrdDtlGpsDTO;
import cn.fl.preloan.IPrjPrdDtlGpsApiService;
import cn.fl.prjprddtlgps.service.IPrjPrdDtlGpsService;
import cn.fl.prjprddtlgps.transform.PrjPrdDtlGpsVOTransform;
import cn.fl.prjprddtlgps.vo.GpsAddressVO;
import cn.fl.prjprddtlgps.vo.PrjPrdDtlGpsVO;
import cn.fl.project.service.IPrjPrdVehInfoService;
import com.alibaba.fastjson.JSON;
import cn.fl.commons.result.ResponseData;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

/**
 * @Description: PRJ_PRD_DTL_GPS（重卡其他GPS） 客户端服务层接口实现
 * @Description: 业务层方法名称前缀：新增：add* 删除：remove* 修改：modify* 查询对象：select* get* 批量：batch* 查询集合：search*
 */
@Service
public class PrjPrdDtlGpsServiceImpl implements IPrjPrdDtlGpsService {

	/**
	 * 日志
	 */
	private static final Logger logger = LoggerFactory.getLogger(PrjPrdDtlGpsServiceImpl.class);
	
	/**
	 * TODO 自定义 API 暴露服务
	 */
	@Autowired
	private IPrjPrdDtlGpsApiService prjPrdDtlGpsApiService;


	@Autowired//by lgj
	private IPrjPrdVehInfoService prjPrdVehInfoService;
	@Autowired
	private ISysFilesApiService sysFilesApiService;

	@Autowired
	private ISysUsrApiService sysUsrApiService;

	@Autowired
	private IDeviceInfoApiService deviceInfoApiService;

	@Override
	public PrjPrdDtlGpsVO selectById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.info(logger, "selectById", "主键参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return null;
		}
		//TODO 业务逻辑
//		PrjPrdDtlGpsDTO dto = null;//this.自定义ApiService.selectById(id);
		return null;
//		return PrjPrdDtlGpsVOTransform.toVO(dto);
	}

	@Override
	public Long add(PrjPrdDtlGpsVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.info(logger, "add", "新增对象不能为空!", CurrentThreadContext.getCurrentUserName());
			return null;
		}
		PrjPrdDtlGpsDTO dto = new PrjPrdDtlGpsDTO();
		BeanUtils.copyProperties(entity,dto);
		ResponseData<Long> responseData = prjPrdDtlGpsApiService.add(dto);
		return responseData.getData();
//		return this.prjPrdDtlGpsApiService.add(PrjPrdDtlGpsVOTransform.toDTO(entity));
	}

	@Override
	public boolean removeById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.info(logger, "removeById", "删除主键参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		}
		//return this.prjPrdDtlGpsApiService.removeById(id);
		//TODO 业务逻辑
		return false;
	}
	
	/**
     * 删除
     * @param ids
     * @return
     */
    public boolean removeByIds(List<Long> ids)throws BaseException{
    	if(CollectionUtils.isEmpty(ids)){
    		BaseLogUtils.info(logger, "removeByIds", "删除主键参数集合不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		};
		return false;
    }

	@Override
	public boolean modify(PrjPrdDtlGpsVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.info(logger, "modify", "修改对象参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		}
		PrjPrdDtlGpsDTO dto = new PrjPrdDtlGpsDTO();
		BeanUtils.copyProperties(entity,dto);
		ResponseData responseData = prjPrdDtlGpsApiService.modify(dto);
		if(ResponseData.SUCCESS_CODE.equals(responseData.getCode())){
			return true;
		}
		return false;
//		this.prjPrdDtlGpsApiService.modify(PrjPrdDtlGpsVOTransform.toDTO(entity));
//		return true;
	}

	@Override
	public boolean modifyGpsAudStsByDtlId(Integer audStsCd,Long dtlId) throws BaseException {
		if (null == audStsCd || dtlId==null) {
			BaseLogUtils.info(logger, "modify", "修改对象参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		}
		ResponseData responseData = prjPrdDtlGpsApiService.modifyAudStsByDtlId(String.valueOf(audStsCd),dtlId);
		if(ResponseData.SUCCESS_CODE.equals(responseData.getCode())){
			return true;
		}
		return false;
//		int num = this.prjPrdDtlGpsApiService.modifyGPSAudSts(PrjPrdDtlGpsVOTransform.toDTO(entity));
//		if (num > 0) {
//			return true;
//		} else {
//			return false;
//		}
	}


	@Override
	public Pager searchListPage(Pager page) throws BaseException{
		if(null == page)page = new Pager();
		ResponseData<PrjPrdDtlGpsPageResponseDTO> responseData = this.prjPrdDtlGpsApiService.selectListPage(page.getEveryPage(),page.getCurrentPage(),
				(PrjPrdDtlGpsQueryCondition)page.getCondition());
		PrjPrdDtlGpsPageResponseDTO response = responseData.getData();
		if(response!=null&&CollectionUtils.isNotEmpty(response.getList())){
			Pager pager = new Pager();
			List<PrjPrdDtlGpsDTO> gpsDTOList = response.getList();
			List<PrjPrdDtlGpsVO> list = new ArrayList();
			for(PrjPrdDtlGpsDTO dto : gpsDTOList){
				PrjPrdDtlGpsVO vo = new PrjPrdDtlGpsVO();
				BeanUtils.copyProperties(dto,vo);
				list.add(vo);
			}
			pager.setResultList(list);
			pager.setTotalCount(response.getTotalCount());
			return pager;
		}

		return null;
	}

	@Override
	public List<PrjPrdDtlGpsVO> searchList(PrjPrdDtlGpsQueryCondition condition)
			throws BaseException {

		ResponseData<List<PrjPrdDtlGpsDTO>> responseData = this.prjPrdDtlGpsApiService.selectList(condition);
		List<PrjPrdDtlGpsDTO> gpsDTOList = responseData.getData();
		List<PrjPrdDtlGpsVO> list = new ArrayList();
		if(CollectionUtils.isNotEmpty(gpsDTOList)){
			for(PrjPrdDtlGpsDTO dto : gpsDTOList){
				PrjPrdDtlGpsVO vo = new PrjPrdDtlGpsVO();
				BeanUtils.copyProperties(dto,vo);
				list.add(vo);
			}
		}
		return list;
//		List<PrjPrdDtlGpsDTO> gpsDTOList = this.prjPrdDtlGpsApiService.searchList(condition);
//		return PrjPrdDtlGpsVOTransform.toVOList(gpsDTOList);
	}

	@Override
	public boolean addPrjPrdDtlGpsList(List<PrjPrdDtlGpsVO> prjPrdDtlGpsList)
			throws BaseException {
    	if(CollectionUtils.isEmpty(prjPrdDtlGpsList)){
			BaseLogUtils.info(logger, "addPrjPrdDtlGpsList", "新增对象参数不能为空!", CurrentThreadContext.getCurrentUserName());
    		return false;
		}
    	List<PrjPrdDtlGpsDTO> list = new ArrayList<>(prjPrdDtlGpsList.size());
    	for(PrjPrdDtlGpsVO vo : prjPrdDtlGpsList){
			PrjPrdDtlGpsDTO dto = new PrjPrdDtlGpsDTO();
			BeanUtils.copyProperties(vo,dto);
			list.add(dto);
		}
		ResponseData responseData = this.prjPrdDtlGpsApiService.addBatch(list);
		if(ResponseData.SUCCESS_CODE.equals(responseData.getCode())){
			return true;
		}
		return false;
//		return this.prjPrdDtlGpsApiService.addPrjPrdDtlGpsDTOList(PrjPrdDtlGpsVOTransform.toDTOList(prjPrdDtlGpsList));
	}

	@Override
	public boolean removeByPrjDtlId(Long prjDtlId) throws BaseException {

		ResponseData responseData = this.prjPrdDtlGpsApiService.removeByDtlId(prjDtlId);

		boolean b = deviceInfoApiService.sendDeviceInfo(prjDtlId);
		BaseLogUtils.newLogger("产品明细id:{},发送大数据:{}",prjDtlId,b).info();

		if(ResponseData.SUCCESS_CODE.equals(responseData.getCode())){
			return true;
		}
		return false;
//		return this.prjPrdDtlGpsApiService.removeByPrjDtlId(prjDtlId);
	}

	@Override
	public String compareFilesIsExists() throws BaseException {
		return this.sysFilesApiService.compareFilesIsExists();
	}

	@Override
	public String compareFilesExists() throws BaseException {
		Pager page = new Pager();
		page.setCurrentPage(1);
		page.setEveryPage(5000);
		SysUlFilesRecQueryCondition qc = new SysUlFilesRecQueryCondition();
		qc.setSysCd("11000");
		qc.setIsExists("0");
		page.setCondition(qc);
		page = this.sysFilesApiService.selectSysUlFilesRecByPage(page);
		int count = page.getTotalPage();
		
		FileWriter fw = null;
		try {
			fw = new FileWriter("/data/test.txt");
			for(int i=1;i<=count;i++){
				List<Long> result = this.sysFilesApiService.compareFilesExists(i);
				for (Long id : result) {
					fw.write(id + "\r\n");
				}
			}
			fw.flush();
			fw.close();
		} catch (IOException e) {
			return "failed";
		}
		return "success";
	}
	
	/**
	 * by lgj 修改GPS信息表
	 */
	@Override
	public boolean modifyPrjPrdDtlGpsList(List<PrjPrdDtlGpsVO> volist) throws BaseException {
		if(CollectionUtils.isEmpty(volist)){
			return false;
		}
		List<PrjPrdDtlGpsDTO> dtoList = new ArrayList<>();
		//1.组装GPS信息
		for (PrjPrdDtlGpsVO vo : volist) {
			//返回code 1表示调用成功 0表示调用失败
			DataResultDTO gpsInfo = prjPrdVehInfoService.getGPSInfo(vo.getGpsCardNo());
			PrjPrdDtlGpsDTO dto = new PrjPrdDtlGpsDTO();
			BeanUtils.copyProperties(vo,dto);
			if(gpsInfo.getCode().equals("1")){
				JSONObject jsonObject = (JSONObject) gpsInfo.getData();
				dto.setGpsStsCd(jsonObject.get("isExist").toString());//获取请求状态
				dto.setGpsAddrInfo(jsonObject.get("address").toString());//位置信息
				dto.setLng(jsonObject.get("lng").toString());//经度
				dto.setLat(jsonObject.get("lat").toString());//维度
				dto.setUseTypCd(jsonObject.get("useType").toString());//设备状态
				dto.setOnlineType(jsonObject.get("onlineType").toString());//设备状态
			}
			dtoList.add(dto);

		}
		BaseLogUtils.info(logger, "modifyPrjPrdDtlGpsList", "修改GPS信息请求参数是"+JSON.toJSONString(dtoList));
		ResponseData responseData = this.prjPrdDtlGpsApiService.modifyBatch(dtoList);
		BaseLogUtils.info(logger, "modifyPrjPrdDtlGpsList", "修改GPS信息返回结果是"+JSON.toJSONString(responseData));
		if(ResponseData.SUCCESS_CODE.equals(responseData.getCode())){
			return true;
		}
		return false;
		//2.修改GPS信息
//		BaseLogUtils.info(logger, "modifyPrjPrdDtlGpsList", "修改GPS信息请求参数是"+JSON.toJSONString(dtoList));
//		DataResultDTO modifyPrjPrdDtlGpsList = prjPrdDtlGpsApiService.modifyPrjPrdDtlGpsList(dtoList);
//		BaseLogUtils.info(logger, "modifyPrjPrdDtlGpsList", "修改GPS信息返回结果是"+JSON.toJSONString(modifyPrjPrdDtlGpsList));
//
//		if(modifyPrjPrdDtlGpsList.getCode().equals("0")){
//			return false;
//		}
//		return true;
	}


	/**
	 * 验证GPS卡号是否重复
	 * @param gpsCardNo GPS卡号
	 * @param prjPrdDtlId
	 * @return 0表示占用 1表示未占用 2 数据错误
	 * @throws BaseException
	 */
	@Override
	public Integer checkGPSExist(String gpsCardNo, Long prjPrdDtlId) throws BaseException {
		ResponseData<String> responseData = this.prjPrdDtlGpsApiService.isUsed(gpsCardNo,prjPrdDtlId);
		return Integer.valueOf( responseData.getData());
//		DataResultDTO resultDTO = prjPrdDtlGpsApiService.chacheGpssIsUser(gpsCardNo, prjPrdDtlId);
//		return Integer.valueOf( resultDTO.getCode());
	}

	@Override
	public List<PrjPrdDtlGpsVO> gpsIsExist(Long dtlId, Integer serialNo) throws BaseException {
		PrjPrdDtlGpsQueryCondition gpsQC = new PrjPrdDtlGpsQueryCondition();
		gpsQC.setIsDel(0);
		gpsQC.setPrjDtlId(dtlId);
		gpsQC.setSerialNo(serialNo);
		return this.searchList(gpsQC);
//		List<PrjPrdDtlGpsDTO> gpsDTOList = this.prjPrdDtlGpsApiService.searchList(gpsQC);
//		return PrjPrdDtlGpsVOTransform.toVOList(gpsDTOList);
	}

	/*
	 * 判断数组中是否有重复的值
	 */
	@Override
	public boolean cheakIsRepeat(String[] array) {
		BaseLogUtils.info(logger, "cheakIsRepeat: ", "cheakIsRepeat: " +JSON.toJSONString(array), CurrentThreadContext.getCurrentUserName());
		HashSet<String> hashSet = new HashSet<String>();
		for (int i = 0; i < array.length; i++) {
			if (array[i].equals("0")){
				hashSet.add(i+"0");
			} else {
				hashSet.add(array[i]);
			}

		}
		BaseLogUtils.info(logger, "cheakIsRepeat: ", "cheakIsRepeat1: " +JSON.toJSONString(hashSet), CurrentThreadContext.getCurrentUserName());
		if (hashSet.size() == array.length) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public void batchInsert(List<PrjPrdDtlGpsVO> gpsList) throws BaseException {

		if(CollectionUtils.isEmpty(gpsList)){
			BaseLogUtils.info(logger, "batchInsert", "新增对象参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return ;
		}
		List<PrjPrdDtlGpsDTO> list = new ArrayList<>(gpsList.size());
		for(PrjPrdDtlGpsVO vo : gpsList){
			PrjPrdDtlGpsDTO dto = new PrjPrdDtlGpsDTO();
			BeanUtils.copyProperties(vo,dto);
			list.add(dto);
		}
		this.prjPrdDtlGpsApiService.addBatch(list);
//		this.prjPrdDtlGpsApiService.batchInsert(PrjPrdDtlGpsVOTransform.toDTOList(gpsList));
	}

	@Override
	public void batchInsertWithDel(List<PrjPrdDtlGpsVO> gpsList) throws BaseException {
		if(CollectionUtils.isEmpty(gpsList)){
			BaseLogUtils.info(logger, "batchInsertWithDel", "新增对象参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return ;
		}
		List<PrjPrdDtlGpsDTO> list = new ArrayList<>(gpsList.size());
		for(PrjPrdDtlGpsVO vo : gpsList){
			PrjPrdDtlGpsDTO dto = new PrjPrdDtlGpsDTO();
			BeanUtils.copyProperties(vo,dto);
			list.add(dto);
		}
		ResponseData responseData = this.prjPrdDtlGpsApiService.addBatchWithDel(list);
		if(!ResponseData.SUCCESS_CODE.equals(responseData.getCode())){
			throw new BaseException(responseData.getMessage());
		}
//		this.prjPrdDtlGpsApiService.batchInsertWithDel(PrjPrdDtlGpsVOTransform.toDTOList(gpsList));
	}

	@Override
	public boolean deleteByIdsForCasual(List<Long> dtlIds) throws BaseException {
		if(CollectionUtils.isEmpty(dtlIds)){
			BaseLogUtils.info(logger, "deleteByIdsForCasual", "参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		}

		ResponseData responseData = this.prjPrdDtlGpsApiService.removeByIdsForCasual(dtlIds);
		if(ResponseData.SUCCESS_CODE.equals(responseData.getCode())){
			return true;
		}
		return false;
//		return this.prjPrdDtlGpsApiService.deleteByIdsForCasual(dtlIds);
	}

	@Override
	public List<String> getGpsDevice(Long cstMgrId, String status) throws BaseException {

		List<String> list = new ArrayList<>();
		if(cstMgrId == null ||StringUtils.isBlank(status)){
			BaseLogUtils.info(logger, "getGpsDevice", "查询GPS账号下设备参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return list; // 返回空参
		}
		SysUsrDTO sysUsrDTO = this.sysUsrApiService.selectSysUsrById(cstMgrId, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
		BaseLogUtils.newLogger("getGpsDevice.获取GPS设备参数返回.cstMgrId={},sysUsrDTO={}", cstMgrId, JSON.toJSONString(sysUsrDTO)).info();
		ResponseData<List<GpsDeviceDTO>> responseData = this.prjPrdDtlGpsApiService.getGpsDevice(sysUsrDTO.getUsrNm(),status);
		if(responseData.isSuccess() && CollectionUtils.isNotEmpty(responseData.getData())){
			List<GpsDeviceDTO> gpsDeviceDTOList = responseData.getData();
			for(GpsDeviceDTO dto : gpsDeviceDTOList){
				list.add(dto.getGpsDeviceNo());
			}
		}
		return list;
	}

	@Override
	public GpsAddressVO getGpsAddress(Long cstMgrId, String keyword, String flag) throws BaseException {
		if(cstMgrId == null || StringUtils.isBlank(keyword) || StringUtils.isBlank(flag)){
			BaseLogUtils.info(logger, "getGpsAddress", "查询GPS位置参数不能为空!", CurrentThreadContext.getCurrentUserName());
		}
		SysUsrDTO sysUsrDTO = this.sysUsrApiService.selectSysUsrById(cstMgrId, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
		ResponseData<GpsAddressDTO> responseData = this.prjPrdDtlGpsApiService.getGpsAddress(sysUsrDTO.getUsrNm(),keyword,flag);
		if(responseData.isSuccess()){
			GpsAddressVO vo = new GpsAddressVO();
			GpsAddressDTO dto = responseData.getData();
			String address = this.prjPrdVehInfoService.getAddressByBaiduMap(dto.getLat(),dto.getLon());
			vo.setGpsAddrInfo(address);
			vo.setLat(dto.getLat());
			vo.setLng(dto.getLon());
			String time = dto.getTime();
			Date date = new Date(Long.valueOf(time) * 1000);
			vo.setLastTm(DateUtils.formatDateToString(date,DateUtils.YYYY_MM_DDHHMMSS));
			Date now = new Date();
			/*long fromLastTm = (now.getTime()-date.getTime())/3600000L;
			vo.setFromLastTm(String.valueOf(fromLastTm));*/
			setDayAndHours(vo,now,date);
			return vo;
		}else{
			throw new BaseException(responseData.getMessage());
		}
	}

	@Override
	public void setDeviceAddInfo(Long cstMgrId,List<PrjPrdDtlGpsVO> gpsList) throws BaseException {

		if(CollectionUtils.isEmpty(gpsList)){
			return ;
		}
		for(PrjPrdDtlGpsVO vo : gpsList){
			String gpsCarNo = vo.getGpsCardNo();
			if(StringUtils.isBlank(gpsCarNo) || "0".equals(gpsCarNo)){
				continue;
			}
			try{
				GpsAddressVO gpsAddressVO = this.getGpsAddress(cstMgrId,vo.getGpsCardNo(),"1");
				BeanUtils.copyProperties(gpsAddressVO,vo);
			}catch (BaseException e){
				BaseLogUtils.newLogger("设置GPS设备位置信息错误").error(LogExceptionEnum.API_CODE_0102.getCode(),e);
			}

		}

	}

	/**
	 *
	 * @param vo
	 * @param now 现在的时间
	 * @param date 大数据接口返回的时间
	 */
	private void setDayAndHours(GpsAddressVO vo,Date now,Date date) {
		long different =  now.getTime() - date.getTime();

		long secondsInMilli = 1000;
		long minutesInMilli = secondsInMilli * 60;
		long hoursInMilli = minutesInMilli * 60;
		long daysInMilli = hoursInMilli * 24;

		long elapsedDays = different / daysInMilli;

		different = different % daysInMilli;
		long elapsedHours = different / hoursInMilli;

		String fromLastTm = "";
		if (elapsedDays == 0) {
			// 判断小时是否够一个小时,不够1小时显示1小时
			if (elapsedHours == 0) {
				fromLastTm = "1小时";
			} else {
				fromLastTm = String.format("%s小时", elapsedHours + 1);
			}
		} else {
			if (elapsedHours == 0) {
				fromLastTm = String.format("%s天1小时", elapsedDays);
			} else {
				fromLastTm = String.format("%s天%s小时", elapsedDays,elapsedHours + 1);
			}
		}

		vo.setFromLastTm(fromLastTm);
	}

}
